package com.ruoyi.web.controller.system;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.ArrayList;
import java.util.Date;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.stream.Collectors;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.system.service.ISysUserService;
import com.ruoyi.fun.service.IEcOrderService;
import com.ruoyi.fun.service.IEcProductService;
import com.ruoyi.fun.service.IEcCategoryService;
import com.ruoyi.fun.service.IEcBrandService;
import com.ruoyi.system.service.ISysUserService;
import com.ruoyi.fun.service.IEcUserBrowseHistoryService;
import com.ruoyi.fun.service.IEcRefundService;
import com.ruoyi.fun.domain.EcOrder;
import com.ruoyi.fun.domain.EcProduct;
import com.ruoyi.fun.domain.EcCategory;
import com.ruoyi.fun.domain.EcBrand;
import com.ruoyi.fun.domain.EcRefund;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.fun.domain.EcUserBrowseHistory;

/**
 * 系统仪表板Controller
 * 
 * @author ruoyi
 */
@RestController
@RequestMapping("/system/dashboard")
public class SysDashboardController extends BaseController
{
    @Autowired
    private ISysUserService userService;
    
    @Autowired
    private IEcOrderService orderService;
    
    @Autowired
    private IEcProductService productService;
    
    @Autowired
    private IEcCategoryService categoryService;
    
    @Autowired
    private IEcBrandService brandService;
    
    @Autowired
    private IEcUserBrowseHistoryService userBrowseHistoryService;
    
    @Autowired
    private IEcRefundService refundService;

    /**
     * 获取系统概览数据
     */
    @GetMapping("/overview")
    public AjaxResult getSystemOverview()
    {
        try {
            Map<String, Object> data = new HashMap<>();
            
            // 系统运行时间（模拟数据）
            data.put("uptime", "7天 12小时 30分钟");
            data.put("version", "RuoYi v3.8.5");
            data.put("javaVersion", System.getProperty("java.version"));
            
            // 服务器信息
            Runtime runtime = Runtime.getRuntime();
            long totalMemory = runtime.totalMemory();
            long freeMemory = runtime.freeMemory();
            long usedMemory = totalMemory - freeMemory;
            
            Map<String, Object> serverInfo = new HashMap<>();
            serverInfo.put("totalMemory", totalMemory / 1024 / 1024 + "MB");
            serverInfo.put("usedMemory", usedMemory / 1024 / 1024 + "MB");
            serverInfo.put("freeMemory", freeMemory / 1024 / 1024 + "MB");
            serverInfo.put("cpuCount", runtime.availableProcessors());
            
            data.put("server", serverInfo);
            
            return success(data);
        } catch (Exception e) {
            logger.error("获取系统概览数据失败", e);
            return error("获取系统概览数据失败: " + e.getMessage());
        }
    }
    
    /**
     * 获取统计数据
     */
    @GetMapping("/stats")
    public AjaxResult getStats()
    {
        try {
            Map<String, Object> stats = new HashMap<>();
            Long orgId = getOrgId();
            
            // 获取今日日期范围
            Calendar calendar = Calendar.getInstance();
            calendar.set(Calendar.HOUR_OF_DAY, 0);
            calendar.set(Calendar.MINUTE, 0);
            calendar.set(Calendar.SECOND, 0);
            calendar.set(Calendar.MILLISECOND, 0);
            Date todayStart = calendar.getTime();
            
            calendar.add(Calendar.DAY_OF_MONTH, 1);
            Date todayEnd = calendar.getTime();
            
            // 今日订单统计
            EcOrder orderQuery = new EcOrder();
            orderQuery.setOrgId(orgId);
            List<EcOrder> allOrders = orderService.selectEcOrderList(orderQuery);
            
            // 筛选今日订单
            long todayOrderCount = allOrders.stream()
                .filter(order -> order.getCreateTime() != null && 
                        order.getCreateTime().compareTo(todayStart) >= 0 &&
                        order.getCreateTime().compareTo(todayEnd) < 0)
                .count();
            
            Map<String, Object> orderStats = new HashMap<>();
            orderStats.put("total", todayOrderCount);
            orderStats.put("trend", 0); // 默认为0
            stats.put("orders", orderStats);
            
            // 商品统计
            EcProduct productQuery = new EcProduct();
            productQuery.setOrgId(orgId);
            List<EcProduct> products = productService.selectEcProductList(productQuery);
            
            Map<String, Object> productStats = new HashMap<>();
            productStats.put("total", products.size());
            productStats.put("trend", 0); // 默认为0
            stats.put("products", productStats);
            
            // 用户统计（获取该组织的用户总数）
            SysUser userQuery = new SysUser();
            userQuery.setDeptId(orgId);
            List<SysUser> users = userService.selectUserList(userQuery);
            
            Map<String, Object> userStats = new HashMap<>();
            userStats.put("total", users.size());
            userStats.put("trend", 0); // 默认为0
            stats.put("users", userStats);
            
            // 今日退款统计
            EcRefund refundQuery = new EcRefund();
            refundQuery.setOrgId(orgId);
            List<EcRefund> allRefunds = refundService.selectEcRefundList(refundQuery);
            
            // 筛选今日退款订单
            long todayRefundCount = allRefunds.stream()
                .filter(refund -> refund.getCreateTime() != null && 
                        refund.getCreateTime().compareTo(todayStart) >= 0 &&
                        refund.getCreateTime().compareTo(todayEnd) < 0)
                .count();
            
            Map<String, Object> refundStats = new HashMap<>();
            refundStats.put("total", todayRefundCount);
            refundStats.put("trend", 0); // 默认为0
            stats.put("refunds", refundStats);
            
            return success(stats);
        } catch (Exception e) {
            logger.error("获取统计数据失败", e);
            return error("获取统计数据失败: " + e.getMessage());
        }
    }
    
    /**
     * 获取销售趋势数据（统计订单状态为2、3、4的订单）
     */
    @GetMapping("/sales-trend")
    public AjaxResult getSalesTrend(String period)
    {
        try {
            Long orgId = getOrgId();
            
            List<Map<String, Object>> trendData = new ArrayList<>();
            SimpleDateFormat sdf = new SimpleDateFormat("MM-dd");
            SimpleDateFormat fullSdf = new SimpleDateFormat("yyyy-MM-dd");
            Calendar cal = Calendar.getInstance();
            
            int days = "7d".equals(period) ? 7 : ("30d".equals(period) ? 30 : 90);
            
            for (int i = days - 1; i >= 0; i--) {
                cal.setTime(new Date());
                cal.add(Calendar.DAY_OF_MONTH, -i);
                Date currentDate = cal.getTime();
                
                Map<String, Object> dayData = new HashMap<>();
                dayData.put("date", sdf.format(currentDate));
                
                // 统计当天订单状态为2、3、4的订单数量
                try {
                    // 使用现有方法查询订单列表并统计
                    EcOrder orderQuery = new EcOrder();
                    orderQuery.setOrgId(orgId);
                    List<EcOrder> allOrders = orderService.selectEcOrderList(orderQuery);
                    
                    // 过滤当天的订单，状态为2、3、4
                    int orderCount = 0;
                    String targetDate = fullSdf.format(currentDate);
                    for (EcOrder order : allOrders) {
                        if (order.getCreateTime() != null) {
                            String orderDate = fullSdf.format(order.getCreateTime());
                            if (targetDate.equals(orderDate)) {
                                String status = order.getOrderStatus();
                                if ("2".equals(status) || "3".equals(status) || "4".equals(status)) {
                                    orderCount++;
                                }
                            }
                        }
                    }
                    
                    dayData.put("value", orderCount);
                } catch (Exception e) {
                    logger.warn("统计日期 {} 的订单数量失败: {}", fullSdf.format(currentDate), e.getMessage());
                    dayData.put("value", 0); // 出错时使用0
                }
                
                trendData.add(dayData);
            }
            
            return success(trendData);
        } catch (Exception e) {
            logger.error("获取销售趋势数据失败", e);
            return error("获取销售趋势数据失败: " + e.getMessage());
        }
    }
    
    /**
     * 获取分类分布数据（按商品品牌分组）
     */
    @GetMapping("/category-distribution")
    public AjaxResult getCategoryDistribution()
    {
        try {
            Long orgId = getOrgId();
            
            // 获取本组织的所有商品
            EcProduct productQuery = new EcProduct();
            productQuery.setOrgId(orgId);
            List<EcProduct> products = productService.selectEcProductList(productQuery);
            
            // 按品牌ID分组统计商品数量
            Map<Long, Integer> brandCountMap = new HashMap<>();
            Map<Long, String> brandNameMap = new HashMap<>();
            
            for (EcProduct product : products) {
                Long brandId = product.getBrandId();
                if (brandId != null) {
                    brandCountMap.put(brandId, brandCountMap.getOrDefault(brandId, 0) + 1);
                    
                    // 获取品牌名称（如果还没有获取过）
                    if (!brandNameMap.containsKey(brandId)) {
                        try {
                            EcBrand brand = brandService.selectEcBrandByBrandIdAndOrgId(brandId, orgId);
                            if (brand != null) {
                                brandNameMap.put(brandId, brand.getBrandName());
                            } else {
                                brandNameMap.put(brandId, "未知品牌");
                            }
                        } catch (Exception e) {
                            brandNameMap.put(brandId, "未知品牌");
                        }
                    }
                }
            }
            
            // 转换为图表数据格式，按商品数量排序
            List<Map<String, Object>> categoryData = new ArrayList<>();
            brandCountMap.entrySet().stream()
                .sorted(Map.Entry.<Long, Integer>comparingByValue().reversed())
                .limit(5) // 只取前5个品牌
                .forEach(entry -> {
                    Map<String, Object> item = new HashMap<>();
                    item.put("name", brandNameMap.get(entry.getKey()));
                    item.put("value", entry.getValue());
                    categoryData.add(item);
                });
            
            // 如果没有品牌数据，返回默认数据
            if (categoryData.isEmpty()) {
                Map<String, Object> item = new HashMap<>();
                item.put("name", "暂无数据");
                item.put("value", 0);
                categoryData.add(item);
            }
            
            return success(categoryData);
        } catch (Exception e) {
            logger.error("获取分类分布数据失败", e);
            return error("获取分类分布数据失败: " + e.getMessage());
        }
    }
    
    /**
     * 获取用户活跃度数据（基于用户浏览足迹数据量统计）
     */
    @GetMapping("/user-activity")
    public AjaxResult getUserActivity()
    {
        try {
            Long orgId = getOrgId();
            
            // 获取最近7天的用户活跃度数据
            List<Map<String, Object>> activityData = new ArrayList<>();
            SimpleDateFormat sdf = new SimpleDateFormat("MM-dd");
            Calendar cal = Calendar.getInstance();
            
            for (int i = 6; i >= 0; i--) {
                cal.setTime(new Date());
                cal.add(Calendar.DAY_OF_MONTH, -i);
                Date currentDate = cal.getTime();
                
                // 设置当天的时间范围
                Calendar dayStart = Calendar.getInstance();
                dayStart.setTime(currentDate);
                dayStart.set(Calendar.HOUR_OF_DAY, 0);
                dayStart.set(Calendar.MINUTE, 0);
                dayStart.set(Calendar.SECOND, 0);
                dayStart.set(Calendar.MILLISECOND, 0);
                Date startTime = dayStart.getTime();
                
                Calendar dayEnd = Calendar.getInstance();
                dayEnd.setTime(currentDate);
                dayEnd.set(Calendar.HOUR_OF_DAY, 23);
                dayEnd.set(Calendar.MINUTE, 59);
                dayEnd.set(Calendar.SECOND, 59);
                dayEnd.set(Calendar.MILLISECOND, 999);
                Date endTime = dayEnd.getTime();
                
                // 获取当天的浏览足迹数据量
                EcUserBrowseHistory historyQuery = new EcUserBrowseHistory();
                historyQuery.setOrgId(orgId);
                List<EcUserBrowseHistory> allHistories = userBrowseHistoryService.selectEcUserBrowseHistoryList(historyQuery);
                
                // 筛选当天的浏览记录
                long dayBrowseCount = allHistories.stream()
                    .filter(history -> history.getBrowseTime() != null &&
                            history.getBrowseTime().compareTo(startTime) >= 0 &&
                            history.getBrowseTime().compareTo(endTime) <= 0)
                    .count();
                
                Map<String, Object> dayData = new HashMap<>();
                dayData.put("date", sdf.format(currentDate));
                dayData.put("value", dayBrowseCount);
                activityData.add(dayData);
            }
            
            return success(activityData);
        } catch (Exception e) {
            logger.error("获取用户活跃度数据失败", e);
            return error("获取用户活跃度数据失败: " + e.getMessage());
        }
    }
    

    
    /**
     * 获取最近订单数据（显示该组织最近3次订单）
     */
    @GetMapping("/recent-orders")
    public AjaxResult getRecentOrders()
    {
        try {
            Long orgId = getOrgId();
            
            // 查询该组织的所有订单
            EcOrder orderQuery = new EcOrder();
            orderQuery.setOrgId(orgId);
            List<EcOrder> allOrders = orderService.selectEcOrderList(orderQuery);
            
            // 按创建时间倒序排序，取最近3条
            List<EcOrder> recentOrders = allOrders.stream()
                .sorted((o1, o2) -> {
                    if (o1.getCreateTime() == null && o2.getCreateTime() == null) return 0;
                    if (o1.getCreateTime() == null) return 1;
                    if (o2.getCreateTime() == null) return -1;
                    return o2.getCreateTime().compareTo(o1.getCreateTime());
                })
                .limit(3)
                .collect(Collectors.toList());
            
            // 转换为前端需要的格式
            List<Map<String, Object>> orderData = new ArrayList<>();
            for (EcOrder order : recentOrders) {
                Map<String, Object> item = new HashMap<>();
                item.put("orderNo", order.getOrderNo() != null ? order.getOrderNo() : "N/A");
                item.put("totalAmount", order.getTotalAmount() != null ? order.getTotalAmount() : new java.math.BigDecimal("0"));
                item.put("createTime", order.getCreateTime());
                item.put("orderStatus", order.getOrderStatus());
                orderData.add(item);
            }
            
            // 如果没有订单数据，返回空列表
            if (orderData.isEmpty()) {
                logger.info("该组织暂无订单数据");
            }
            
            return success(orderData);
        } catch (Exception e) {
            logger.error("获取最近订单数据失败", e);
            return error("获取最近订单数据失败: " + e.getMessage());
        }
    }
    
    /**
     * 获取热销商品数据
     */
    @GetMapping("/hot-products")
    public AjaxResult getHotProducts()
    {
        try {
            Long orgId = getOrgId();
            EcProduct productQuery = new EcProduct();
            productQuery.setOrgId(orgId);
            List<EcProduct> products = productService.selectEcProductList(productQuery);
            
            // 按销量从高到低排序，取前5个商品作为热销商品
            List<Map<String, Object>> hotProducts = products.stream()
                .sorted((p1, p2) -> {
                    Long sales1 = p1.getSaleCount() != null ? p1.getSaleCount() : 0L;
                    Long sales2 = p2.getSaleCount() != null ? p2.getSaleCount() : 0L;
                    return Long.compare(sales2, sales1); // 降序排列
                })
                .limit(5)
                .map(product -> {
                    Map<String, Object> item = new HashMap<>();
                    item.put("name", product.getProductName());
                    item.put("sales", product.getSaleCount() != null ? product.getSaleCount() : 0);
                    item.put("amount", product.getPrice() != null ? product.getPrice() : new java.math.BigDecimal("0"));
                    return item;
                })
                .collect(Collectors.toList());
            
            // 如果没有商品数据，返回模拟数据
            if (hotProducts.isEmpty()) {
                String[] defaultProducts = {"iPhone 15", "华为Mate60", "小米14", "MacBook Pro", "iPad Air"};
                for (String name : defaultProducts) {
                    Map<String, Object> item = new HashMap<>();
                    item.put("name", name);
                    item.put("sales", 0);
                    item.put("amount", 0);
                    hotProducts.add(item);
                }
            }
            
            return success(hotProducts);
        } catch (Exception e) {
            logger.error("获取热销商品数据失败", e);
            return error("获取热销商品数据失败: " + e.getMessage());
        }
    }
}